<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select v-model="formData.parentId" :data="deptTree" :props="defaultProps" check-strictly
          default-expand-all placeholder="" value-key="deptId" />
      </el-form-item>
      <el-form-item label="企业名称" prop="name">
        <el-input v-model="formData.name" placeholder="" />
      </el-form-item>
      <el-form-item label="注册时间" prop="registerTime">
        <!-- <el-input v-model="formData.registerTime" placeholder="" /> -->
        <!-- <el-datetime-picker
          v-model="formData.registerTime"
          type="date"
          placeholder=""
           format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      /> -->
        <el-date-picker v-model="formData.registerTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item label="企业类型" prop="corpType">
        <el-select v-model="formData.corpType" clearable placeholder="">
          <el-option v-for="item in enterTypeList.list" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="area">
        <el-cascader v-model="formData.area" :options="areaTreeList" :props="{
          children: 'children',
          label: 'name',
          value: 'id',
          emitPath: true // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
        }" placeholder="" value-key="id" ref="areaRef" />
        <!-- <el-select v-model="formData.provinceId" clearable placeholder="">
          <el-option
            v-for="item in provinceList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="formData.cityId" v-if="formData.provinceId" clearable placeholder="">
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="formData.areaId" v-if="formData.cityId" clearable placeholder="">
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
      </el-form-item>
      <el-form-item label="企业地址" prop="corpAddress">
        <el-input v-model="formData.corpAddress" placeholder="" />
      </el-form-item>
      <el-form-item label="社会代码" prop="societyCode">
        <el-input v-model="formData.societyCode" placeholder="" />
      </el-form-item>
      <el-form-item label="法人名称" prop="userName">
        <el-input v-model="formData.userName" placeholder="" />
      </el-form-item>
      <el-form-item label="联系类型" prop="contactTag">
        <!-- <el-input v-model="formData.contactTag" placeholder="" /> -->
        <el-select v-model="formData.contactTag" clearable placeholder="">
          <el-option v-for="item in phoneList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="formData.phone" placeholder="" />
      </el-form-item>
      <el-form-item label="员工账号数" prop="userCount">
        <el-input v-model="formData.userCount" placeholder="" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" clearable placeholder="">
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否是燃气企业" prop="gasTag">
        <el-select v-model="formData.gasTag" clearable placeholder="">
          <el-option v-for="item in gasTagList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="行业类别" prop="industryType">
        <el-select v-model="formData.industryType" clearable placeholder="">
          <el-option v-for="item in workTypeList.list" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="上传logo" prop="corpLogo">
        <UploadImg v-model="formData.corpLogo" :limit="1" />
      </el-form-item>
      <el-form-item label="上传营业执照" prop="businessFile">
        <UploadImg v-model="formData.businessFile" :limit="1" />
      </el-form-item>
      <el-form-item label="排序" prop="phone">
        <el-input-number v-model="formData.sort" placeholder="" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { CommonStatusEnum } from '@/utils/constants'
import { FormRules } from 'element-plus'

defineOptions({ name: 'SystemDeptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: '',
  parentId: undefined,
  name: undefined,
  sort: undefined,
  leaderUserId: undefined,
  phone: undefined,
  email: undefined,
  status: '',
  area: [],
  corpLogo: '',
  businessFile: ''
})
const areaRef = ref()
const formRules = reactive<FormRules>({
  parentId: [{ required: true, message: '不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  // email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phone: [
    { message: '不能为空', trigger: 'blur' }
  ],
  registerTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '不能为空', trigger: 'blur' }],
  corpType: [{ required: true, message: '不能为空', trigger: 'blur' }],
  area: [{ required: true, message: '不能为空', trigger: 'blur' }],
  corpAddress: [{ required: true, message: '不能为空', trigger: 'blur' }],
  societyCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
  userName: [{ required: true, message: '不能为空', trigger: 'blur' }],
  contactTag: [{ required: true, message: '不能为空', trigger: 'blur' }],
  userCount: [{ required: true, message: '不能为空', trigger: 'blur' }],
  gasTag: [{ required: true, message: '不能为空', trigger: 'blur' }],
  industryType: [{ required: true, message: '不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const deptTree = ref() // 树形结构
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const enterTypeList = ref({})
const workTypeList = ref({})

const areaTreeList = ref()

const gasTagList = [{ label: '是', value: '1' }, { label: '否', value: '2' }]
const statusList = [{ label: '启用', value: 0 }, { label: '禁用', value: 1 }]

const phoneList = [{ label: '手机', value: '1' }, { label: '座机', value: '0' }]

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeptApi.getDept(id)
      formData.value.area = [formData.value.provinceId, formData.value.cityId, formData.value.areaId]
      formData.value.corpLogo = formData.value.corpLogo && JSON.parse(formData.value.corpLogo)
      formData.value.businessFile = formData.value.corpLogo && JSON.parse(formData.value.corpLogo)

    } finally {
      formLoading.value = false
    }
  }
  // 获得用户列表
  userList.value = await UserApi.getSimpleUserList()
  enterTypeList.value = await DeptApi.getDictPage('bussiness_type')
  workTypeList.value = await DeptApi.getDictPage('work_type')
  areaTreeList.value = await DeptApi.getSystemTree()
  // 获得部门树
  await getTree()

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log(formData.value)
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    formData.value.provinceId = formData.value.area[0]
    formData.value.cityId = formData.value.area[0]
    formData.value.areaId = formData.value.area[0]
    formData.value.corpLogo = formData.value.corpLogo && JSON.stringify(formData.value.corpLogo)
    formData.value.businessFile = formData.value.corpLogo && JSON.stringify(formData.value.corpLogo)
    const data = formData.value as unknown as DeptApi.DeptVO
    if (formType.value === 'create') {
      await DeptApi.createDept(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeptApi.updateDept(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: '',
    parentId: undefined,
    name: undefined,
    sort: undefined,
    leaderUserId: undefined,
    phone: undefined,
    email: undefined,
    status: ''
  }
  formRef.value?.resetFields()
}

/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  const data = await DeptApi.getSimpleDeptList()
  let dept: Tree = { id: 0, name: '顶级部门', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}
</script>
